package com.nciae.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.ParserConfig;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nciae.po.DormitoryHead;
import com.nciae.dao.DormitoryHeadMapper;
import com.nciae.po.User;
import com.nciae.service.IDormitoryHeadService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nciae.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Guoliyu
 * @since 2022-03-30
 */
@Service
public class DormitoryHeadServiceImpl extends ServiceImpl<DormitoryHeadMapper, DormitoryHead> implements IDormitoryHeadService {

    @Autowired
    private IUserService userService;

    @Override
    public List<DormitoryHead> findAll(int index, int capacity, String username) {
        List<DormitoryHead> dormitoryHeads = baseMapper.findAll(index, capacity, username);
        for(DormitoryHead dormitoryHead : dormitoryHeads) {
            User user = userService.findUserById(dormitoryHead.getId());
            dormitoryHead.setUser(user);
        }
        return dormitoryHeads;
    }

    @Override
    public void add(DormitoryHead dormitoryHead) {
        ParserConfig.getGlobalInstance().addAccept("com.nciae.po.User");
        String userJson = dormitoryHead.getUserJson();
        User user = (User) JSONObject.parse(userJson);
        userService.add(user);
        dormitoryHead.setId(user.getId());
        baseMapper.insert(dormitoryHead);
    }

    @Override
    public void update(DormitoryHead dormitoryHead) {
        System.out.println(dormitoryHead);
        String userJson = dormitoryHead.getUserJson();
        User user = (User) JSONObject.parse(userJson);
        user.setId(dormitoryHead.getId());
        userService.update(user);
        baseMapper.updateById(dormitoryHead);
    }

    @Override
    public void delete(Long id) {
        userService.delete(id);
        baseMapper.deleteById(id);
    }

    @Override
    public DormitoryHead findDormitoryById(Long id) {
        DormitoryHead dormitoryHead = baseMapper.selectById(id);
        User user = userService.findUserById(id);
        if (!Objects.isNull(dormitoryHead)) {
            dormitoryHead.setUser(user);
        }
        return dormitoryHead;
    }
}
